package com.ailot.cloud.base.security.handler;

import cn.hutool.http.HttpStatus;
import com.ailot.cloud.base.common.dto.Result;
import com.ailot.cloud.base.security.utils.ResponseUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@Component
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint {


    @Override
    public void commence(HttpServletRequest request, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        log.error("认证异常：{}",e.getMessage());
        Result<String> result = Result.fail("认证异常");
        if (e != null) {
            result.setMsg(e.getMessage());
            result.setData(e.getLocalizedMessage());
        }
        httpServletResponse.setStatus(HttpStatus.HTTP_UNAUTHORIZED);
        ResponseUtil.response(httpServletResponse, result);
    }


}
